﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace JESAI.Common.Util
{
    /// <summary>
    /// FTP通用类
    /// </summary>

    public class FTPHelper
    {
        private string port;
        private string ftpHostIP;
        private string userName;
        private string password;

        public FTPHelper(string _port, string _ftpHostIP, string _userName, string _password)
        {
            port = _port;
            ftpHostIP = _ftpHostIP;
            userName = _userName;
            password = _password;
        }
        /// <summary>
        /// 上传本地文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="targetDir">目标文件夹</param>
        public void UploadFile(string filePath, string targetDir)
        {
            FileInfo fileinfo = new FileInfo(filePath);
            //1. check target
            string target;
            if (targetDir.Trim() == "")
            {
                return;
            }
            string filename = fileinfo.Name;
            if (!string.IsNullOrEmpty(filename))
                target = filename;
            else
                target = Guid.NewGuid().ToString() + "." + filePath.Split('.')[1];  //使用临时文件名

            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + targetDir + "/" + target;
            MakeDir(targetDir);
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex) { throw ex; }
                finally
                {
                    fs.Close();
                }

            }
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">FileInfo</param>
        /// <param name="targetDir">目标文件夹</param>
        public void UploadFileInfo(FileInfo fileinfo, string targetDir)
        {
            if (targetDir.Trim() == "")
            {
                return;
            }
            string filename = fileinfo.Name;

            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + targetDir + "/" + filename;
            MakeDir(targetDir);
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;

            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex) { throw ex; }
                finally
                {
                    fs.Close();
                }

            }
        }

        /// <summary>
        /// 上传文件（文件流的形式）
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <param name="targetDir">目标文件夹</param>
        /// <param name="fileName">文件名</param>
        public void UploadFileStream(Stream fs, string targetDir, string fileName)
        {
            if (targetDir.Trim() == "")
            {
                return;
            }
            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + targetDir + "/" + fileName;
            MakeDir(targetDir);
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //设置FTP命令 设置所要执行的FTP命令，
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fs.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;
            //打开一个文件流 (System.IO.FileStream) 去读上传的文件         
            try
            {
                //把上传的文件写入流
                using (Stream rs = ftp.GetRequestStream())
                {
                    do
                    {
                        //每次读文件流的2KB
                        dataRead = fs.Read(content, 0, BufferSize);
                        rs.Write(content, 0, dataRead);
                    } while (!(dataRead < BufferSize));
                    rs.Close();
                }

            }
            catch (Exception ex) { throw ex; }
            finally
            {
                fs.Close();
            }

        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">本地文件夹</param>
        /// <param name="FtpDir">FTP文件夹</param>
        /// <param name="FtpFile">FTP文件名</param>
        /// <param name="downLoadFileName">下载的文件名</param>
        public void DownloadFile(string localDir, string FtpDir, string FtpFile, string downLoadFileName = null)
        {
            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + FtpDir + "/" + FtpFile;
            if (string.IsNullOrWhiteSpace(downLoadFileName))
            {
                downLoadFileName = Guid.NewGuid().ToString() + "." + FtpFile.Split('.')[1];
            }

            string localfile = localDir + @"\" + downLoadFileName;

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            ftp.KeepAlive = true;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            File.Delete(localfile);
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }
        }


        /// <summary>
        /// 下载文件，字节
        /// </summary>
        /// <param name="FtpDir">FTP文件夹</param>
        /// <param name="FtpFile">FTP文件名</param>
        /// <returns></returns>
        public byte[] DownloadFileBytes(string FtpDir, string FtpFile)
        {
            byte[] bts;
            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + FtpDir + "/" + FtpFile;
            string tmpname = Guid.NewGuid().ToString();

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (MemoryStream fs = new MemoryStream())
                    {
                        try
                        {
                            //byte[] buffer = new byte[2048];
                            //int read = 0;
                            //do
                            //{
                            //    read = responseStream.Read(buffer, 0, buffer.Length);
                            //    fs.Write(buffer, 0, read);
                            //} while (!(read == 0));
                            //responseStream.Close();
                            //byte[] mbt = new byte[fs.Length];
                            //fs.Read(mbt, 0, mbt.Length);

                            //bts = mbt;


                            byte[] buffer = new byte[1024];
                            while (true)
                            {
                                int sz = responseStream.Read(buffer, 0, 1024);
                                if (sz == 0) break;
                                fs.Write(buffer, 0, sz);
                            }
                            responseStream.Close();
                            fs.Position = 0;

                            var bytes = new byte[(int)fs.Length];
                            fs.Read(bytes, 0, bytes.Length);
                            bts = bytes;
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            fs.Close();
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }

            ftp = null;
            return bts;
        }
        /// <summary>
        /// 下载文件，字节
        /// </summary>
        /// <param name="FtpDir">FTP文件夹</param>
        /// <param name="FtpFile">FTP文件名</param>
        /// <returns></returns>
        public Stream DownloadFileStream(string FtpDir, string FtpFile)
        {
            string URI = "FTP://" + ftpHostIP + ":" + port + "/" + FtpDir + "/" + FtpFile;
            string tmpname = Guid.NewGuid().ToString();
            MemoryStream fs = new MemoryStream();
            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file                    
                    byte[] buffer = new byte[2048];
                    int read = 0;
                    do
                    {
                        read = responseStream.Read(buffer, 0, buffer.Length);
                        fs.Write(buffer, 0, read);
                    } while (!(read == 0));
                    responseStream.Close();
                }

                response.Close();
            }

            ftp = null;
            return fs;
        }
        /// <summary>
        /// 搜索远程文件
        /// </summary>
        /// <param name="targetDir"></param>
        /// <param name="SearchPattern"></param>
        /// <returns></returns>
        public List<string> ListDirectory(string targetDir, string SearchPattern)
        {
            List<string> result = new List<string>();
            try
            {
                string URI = "FTP://" + ftpHostIP + ":" + port + "/" + targetDir + "/" + SearchPattern;

                System.Net.FtpWebRequest ftp = GetRequest(URI);
                ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
                ftp.UsePassive = true;
                ftp.UseBinary = true;


                string str = GetStringResponse(ftp);
                str = str.Replace("\r\n", "\r").TrimEnd('\r');
                str = str.Replace("\n", "\r");
                if (str != string.Empty)
                    result.AddRange(str.Split('\r'));

                return result;
            }
            catch { }
            return null;
        }

        private static string GetStringResponse(FtpWebRequest ftp)
        {
            string result = "";
            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                long size = response.ContentLength;
                using (Stream datastream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
                    {
                        result = sr.ReadToEnd();
                        sr.Close();
                    }

                    datastream.Close();
                }

                response.Close();
            }

            return result;
        }
        public void FtpMakeDir(string dir)
        {
            string uri = "ftp://" + ftpHostIP + ":" + port + "/" + dir;
            FtpWebRequest req = GetRequest(uri);
            req.Method = WebRequestMethods.Ftp.MakeDirectory;
            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 在ftp服务器上创建目录
        /// </summary>
        /// <param name="dirName">创建的目录名称</param>
        public void MakeDir(string dirName)
        {
            string[] dirs = dirName.Split('/');
            string curDir = "/";
            for (int i = 0; i < dirs.Length; i++)
            {
                string dir = dirs[i];
                //如果是以/开始的路径,第一个为空    
                if (dir != null && dir.Length > 0)
                {
                    try
                    {
                        curDir += dir + "/";
                        FtpMakeDir(curDir);
                    }
                    catch (Exception)
                    { }
                }
            }



            //try
            //{

            //    var ms = dirName.Split('/');
            //    var dir = "";
            //    string pre = "";
            //    foreach (var mm in ms)
            //    {
            //        dir = dir + mm + "/";
            //        if (!ftpIsExistsFile(pre, mm))
            //        {

            //            string uri = "ftp://" + ftpHostIP + ":" + port + "/" + dir;
            //            System.Net.FtpWebRequest ftp = GetRequest(uri);
            //            ftp.Method = WebRequestMethods.Ftp.MakeDirectory;

            //            FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
            //            response.Close();
            //        }
            //        pre = dir;
            //    }

            //}
            //catch (Exception ex)
            //{
            //    throw new Exception(ex.Message);
            //}

        }
        /// <summary>
        ///在ftp服务器上创建文件目录
        /// </summary>
        /// <param name="dirName">文件目录</param>
        /// <returns></returns>
        public bool MakeDirs(string dirName)
        {
            try
            {
                string url = "ftp://" + ftpHostIP + ":" + port + "/" + dirName;
                bool b = !Directory.Exists(url);//RemoteFtpDirExists(url);
                if (b)
                {
                    return true;
                }
                //string url = "ftp://" + ftpHostIP + ":" + port + "/" + dirName;
                FtpWebRequest reqFtp = GetRequest(url);
                reqFtp.UseBinary = true;
                // reqFtp.KeepAlive = false;
                reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFtp.Credentials = new NetworkCredential(userName, password);
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
        /// <summary>
        /// 判断ftp上的文件目录是否存在
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool RemoteFtpDirExists(string uri)
        {

            FtpWebRequest reqFtp = GetRequest(uri);
            reqFtp.UseBinary = true;
            reqFtp.Credentials = new NetworkCredential(userName, password);
            reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse resFtp = null;
            try
            {
                resFtp = (FtpWebResponse)reqFtp.GetResponse();
                FtpStatusCode code = resFtp.StatusCode;//OpeningData
                resFtp.Close();
                return true;
            }
            catch
            {
                if (resFtp != null)
                {
                    resFtp.Close();
                }
                return false;
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="dirName">创建的目录名称</param>
        /// <param name="filename">文件名</param>
        public void DelFile(string dirName, string filename)
        {
            try
            {
                string uri = "ftp://" + ftpHostIP + ":" + port + "/";
                if (!string.IsNullOrEmpty(dirName))
                {
                    uri += dirName + "/";
                }
                uri += filename;
                System.Net.FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dirName">创建的目录名称</param>
        public void DelDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpHostIP + ":" + port + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 文件重命名
        /// </summary>
        /// <param name="currentFilename">当前目录名称</param>
        /// <param name="newFilename">重命名目录名称</param>
        public void Rename(string currentFilename, string newFilename)
        {
            try
            {

                FileInfo fileInf = new FileInfo(currentFilename);
                string uri = "ftp://" + ftpHostIP + ":" + port + "/" + fileInf.Name;
                System.Net.FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.Rename;

                ftp.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private FtpWebRequest GetRequest(string URI)
        {

            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
            //提供身份验证信息
            result.Credentials = (NetworkCredential)NetworkCredentialSingleton.GetInstance(userName, password)[userName];
            //设置请求完成之后是否保持到FTP服务器的控制连接，默认值为true
            result.KeepAlive = false;
            return result;
        }
        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool ftpIsExistsFile(string preDir, string dirName)
        {
            bool flag = false;
            try
            {
                string pre = string.IsNullOrWhiteSpace(preDir) == true ? preDir : "/" + preDir;
                pre = pre.TrimEnd('/');
                string uri = "ftp://" + ftpHostIP + ":" + port + pre;
                System.Net.FtpWebRequest ftp = GetRequest(uri);
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;
                ftp.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string line = reader.ReadLine();
                if (line != null)
                {
                    flag = true;
                }
                //while (line != null)
                //{
                //    if (line == dirName)
                //    {
                //        flag = true;
                //        break;
                //    }
                //    line = reader.ReadLine();
                //}
                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return flag;
        }
    }
}
